package com.atguigu.ucenterservice.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.ucenterservice.entity.UcenterMember;
import com.atguigu.ucenterservice.service.UcenterMemberService;
import com.atguigu.ucenterservice.utils.ConstantYmlUtil;
import com.atguigu.ucenterservice.utils.HttpClientUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;


@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {


    @Autowired
    private UcenterMemberService memberService;



    @GetMapping ("callback")
    public String callback(String code, String state, HttpSession session){

        //得到授权的临时票据code
//        System.out.println("code = " + code);
//        System.out.println("state = " + state);

        //向认证服务器发送请求换取access_token
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";

        String accessTokenUrl = String.format(baseAccessTokenUrl,
                ConstantYmlUtil.WX_OPEN_APP_ID,
                ConstantYmlUtil.WX_OPEN_APP_SECRET,
                code);
        String result = null;
        try {
            result = HttpClientUtils.get(accessTokenUrl);
//            System.out.println("accessToken " + result);
        } catch (Exception e) {
            throw new GuliException(20001, "获取accessToken失败 " + e.getMessage());
        }
        //解析json字符串
        Gson gson = new Gson();
        HashMap map = gson.fromJson(result, HashMap.class);
        String access_token = (String)map.get("access_token");
        String openid = (String)map.get("openid");

        //查询数据库当前用用户是否曾经使用过微信登录
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("openid", openid);
        UcenterMember member = memberService.getOne(wrapper);

        if (member == null){

            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";

            String userInfoUrl = String.format(baseUserInfoUrl,
                    access_token,
                    openid);

            String resultUserInfo = null;
            try {
                resultUserInfo = HttpClientUtils.get(userInfoUrl);
//                System.out.println("userInfo: "+ resultUserInfo);
            } catch (Exception e) {
                throw new GuliException(20001, "获取UserInfo失败" + e.getMessage());
            }

            HashMap userInfo = gson.fromJson(resultUserInfo, HashMap.class);
            String nickname = (String)userInfo.get("nickname");
            String headimgurl = (String) userInfo.get("headimgurl");

            member = new UcenterMember();

            member.setNickname(nickname);
            member.setAvatar(headimgurl);
            member.setOpenid(openid);

            memberService.save(member);

        }
        //使用jwt根据member对象生成token字符串
        String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());


        return "redirect:http://localhost:3000?token=" + jwtToken;
    }



    @GetMapping("login")
    public String WxCode(){
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //对redirect_url进行URLEncoder编码
        String redirectUrl =  ConstantYmlUtil.WX_OPEN_REDIRECT_URL;


        try {
            redirectUrl =  URLEncoder.encode(redirectUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new GuliException(20001, e.getMessage());
        }
        //设置%s里面值
        String url = String.format(baseUrl,
                ConstantYmlUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu");
        //重定向到请求微信地址里面
        return  "redirect:" + url;

    }





}
